<?php

namespace app\admin\controller;

use app\api\model\ConfigAlipay;
use app\api\model\Withdraw;
use app\api\model\WithdrawMerge;
use app\api\model\YaoqingRecords as Income;
use think\Db;
use think\Session;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Pay;

class Balancenottransfer extends Common
{
    public function withdraw(): string
    {
        $admin = Session::get('admin', 'mmjtAdmin');
        $order = input('order') ? input('order') : 'desc';
        $this->assign('order', input('order') ? input('order') : 1);
        if ($order == 1) {
            $order = 'desc';
        } else if ($order == 2) {
            $order = 'asc';
        }
        $paymethod = input('paymethod') ?: 1;//默认支付宝
        $where['t1.paymethod'] = $paymethod;
        $where['t1.channel'] = 1;
        $this->assign('paymethod', $paymethod);

        $date = date('Y-m-d');
    
        $yesterday_start = strtotime('-1 day', strtotime($date));
        $yesterday_date = date('Y-m-d', $yesterday_start);

        $where['t2.delete_time'] = 0;

        $state = input('state') ?: 0;
        $where['t1.state'] = $state;

        $moneyArea = [[0,99.99],[100,299.99],[300,599.99],[600,999.99],[999,99999999]];
        $money = input('money') ?: 0;
        if($money){
            $totalwhere['total'] = ['between', $moneyArea[$money - 1]];
        }else{
            $totalwhere = [];
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
        }


        $subQuery = Db::table('withdraw t1')
            ->field('t1.userid, t2.name, t2.phone, sum(t1.money) as total')
            ->join('user t2', 't2.id = t1.userid')
            ->where($where)
            ->group('t1.userid')
            ->fetchSql(true)
            ->select();

        $withdrawcount = Db::table("($subQuery) a")
            ->where($totalwhere)
            ->count();
        $withdrawsum = Db::table("($subQuery) a")
            ->where($totalwhere)
            ->sum('total');
        $this->assign('withdrawcount', $withdrawcount);
        $this->assign('withdrawsum', $withdrawsum);

        $withdrawcount2 = 0;
        $data = Db::table("($subQuery) a")
            ->where($totalwhere)
            ->order('total desc,userid asc')
            ->select();
        foreach ($data as $key => $value) {
            $maxValue = 200;
            $rateMax = ceil($value['total'] / $maxValue);
            $withdrawcount2 += $rateMax;
        }
        $this->assign('withdrawcount2', $withdrawcount2);

        $data = Db::table("($subQuery) a")
            ->where($totalwhere)
            ->order('total ' . $order . ',userid asc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])->each(function ($item, $yesterday_date) {
                $date = date('Y-m-d');

                $yesterday_start = strtotime('-1 day', strtotime($date));
                $yesterday_date = date('Y-m-d', $yesterday_start);

                $user_balance = Db::name('user_balance')->where(['user_id' => $item['userid'], 'date' => $yesterday_date])->cache(3600)->find();
                $user_balance_today = Db::name('user_balance')->where(['user_id' => $item['userid'], 'date' => $date])->cache(3600)->find();
                
                $item['score_yesterday'] = $user_balance ? $user_balance['score'] : 0;
                $item['score_today'] = $user_balance_today ? $user_balance_today['score'] : 0;
                
                //$item['income_yesterday'] = $user_balance ? $user_balance['income'] : 0;
                
                if ($user_balance) {
                    $item['income_yesterday'] = $user_balance['income'];
                } else {
                    $item['income_yesterday'] = Db::name('yaoqing_records')
                        ->where(['uid' => $item['userid'], 'type' => 1, 'data' => 0])->whereTime('time', 'yesterday')->cache(3600)->sum('money');
                }
                $item['money'] = $item['total'];

                // $item['money'] = Db::name('withdraw')->where(['userid' => $item['userid'], 'state' => ['in', [0,1]]])->whereTime('create_time', 'yesterday')->cache(3600)->sum('money');

                $item['warn'] = $item['score_yesterday'] + $item['income_yesterday'] - $item['score_today'] < $item['money'] * 5;

                return $item;
            });

        $this->assign('data', $data);
        $this->assign('admin', $admin);
        $page = $data->render();
        $this->assign('page', $page);
    

        $this->assign('start', date('Y-m-d H:i:s', $yesterday_start));
        $yesterday_end = date('Y-m-d H:i:s', ($yesterday_start + 86399));
        $this->assign('end', $yesterday_end);
        
        $this->assign('state', $state);
        $this->assign('money', $money);

        return $this->fetch();
    }

    public function allWithdraw()
    {
        $user_id = input('user_id');

        if (request()->isAjax()) {
            $admin = session('admin', '', 'mmjtAdmin');

            $admin = Db::name('admin')->find($admin['id']);

            if ($admin['type'] != 1) {
                return ['err' => '无权限'];
            }


            $post = input('post.');


            $state = $post['state'];


            $user = Db::name('user')->find($user_id);
            if (!$user) return ['err' => '用户不存在'];

            $withdraw = Db::name('withdraw_merge')->where(['userid' => $user_id, 'state' => 0])->whereTime('create_time', 'yesterday')->find();
            if (!$withdraw) return ['err' => '未有待审核的提现'];

            $WithdrawModel = new Withdraw;
            $WithdrawMergeModel = new WithdrawMerge;
            $IncomeModel = new Income;
            $current_time = time();

            $pass_total = 0;
            $pass = [];
            $miss = false;
            $updates = [];

            // 启动事务
            Db::startTrans();
            try {
                if ($state == 2) {
                    $content = '提现申请驳回';

                    if (isset($post['reason']) && $post['reason']) {
                        $content .= '。理由：' . $post['reason'];
                    }
                    $miss = true;

                    $ret = '提现已拒绝';
                } else {
                    $datas = json_decode($withdraw['data'], true);

                    $datas['order_id'] = $withdraw['id'] . uniqid();

                    $updates = [
                        'id' => $withdraw['id'],
                        'state' => 1,
                        'data' => json_encode($datas, JSON_UNESCAPED_UNICODE),
                        'update_time' => $current_time,
                    ];


                    // 更新提现订单
                    $WithdrawMergeModel->update($updates);

                    $withdraw_ids = explode(',',$withdraw['withdraw_ids']);
                    $passSourse = [];
                    foreach ($withdraw_ids as $value) {
                        $updates['id'] = $value;
                        array_push($passSourse, $updates);
                    }

                    // 更新提现订单
                    $WithdrawModel->saveAll($passSourse);

                    // 添加进平台账单
                    Db::name('platform_balance')->insert([
                        'types' => 1,
                        'money' => $withdraw['money'],
                        'content' => '用户(ID:' . $user_id . ')批量提现',
                        'create_time' => $current_time
                    ]);

                    $ret = '提现成功';

                }

                // 拒绝
                if ($miss) {
                    $balance = Db::name('user')->where(['id' => $user_id])->value('score');

                    $balance = $balance + $withdraw['price'] + $withdraw['shouxu'];

                    $miss_updates = [
                        'id' => $withdraw['id'],
                        'state' => 2,
                        'reason' => $content,
                        'update_time' => $current_time,
                    ];

                    $miss_income = [
                        'uid' => $user_id,
                        'content' => '提现失败返还。' . $content,
                        'money' => $withdraw['price'] + $withdraw['shouxu'],
                        'time' => $current_time,
                        'type' => 1,
                        'balance' => $balance,
                    ];

                    $WithdrawMergeModel->update($miss_updates);

                    $withdraw_ids = explode(',',$withdraw['withdraw_ids']);
                    $missSourse = [];
                    foreach ($withdraw_ids as $value) {
                        $miss_updates['id'] = $value;
                        array_push($missSourse, $miss_updates);
                    }

                    // 更新提现订单
                    $WithdrawModel->saveAll($missSourse);

                    // 添加积分变动记录
                    $IncomeModel->insert($miss_income);

                    // 积分账户修改
                    $miss_total = changefloor($withdraw['price'] + $withdraw['shouxu']);
                    Db::name('user')->where('id', $user_id)->setInc('score', $miss_total);
                    
                    $ret = $content;
                }

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();

                return ['err' => $e->getMessage()];
            }

            $data = ['ret' => $ret];
        } else {
            if (!$user_id) {
                return ['err' => '参数错误'];
            }
            $data = $this->fetch();
        }
        return $data;
    }


    //提现管理
    public function tixian()
    {
        $map = ['t1.channel'=>1];
        $daili = [];    //城市代理管理员查看筛选

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $map['t2.city'] = ['like', $admin['city'] . '%'];
            $daili['t2.city'] = ['like', $admin['city'] . '%'];
        }

        $daili['state'] = '1';

        $type = input('type');
        if ($type == 1) {
            $map['t1.paymethod'] = '0';
        } else if ($type == 2) {
            $map['t1.paymethod'] = '1';
        } else if ($type == 3) {
            $map['t1.state'] = '0';
        } else if ($type == 4) {
            $map['t1.state'] = '1';
        } else if ($type == 5) {
            $map['t1.state'] = '2';
        }

        $search_name = input('param.name','');
        $search_type = input('param.search','');
        $this->assign('search_name', $search_name);
        $this->assign('search_type', $search_type);
        if ($search_name && $search_type) {
            if ($search_type == 'id') {
                $map['t2.' . $search_type] = $search_name;
            } else {
                $map['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
            }
        }
        $yesterday = input('yesterday');
        $start = input('start');
        $end = input('end');
        if($yesterday && !$start && !$end){
            $date = date('Y-m-d');
            $yesterday_start = date('Y-m-d', strtotime('-1 day', strtotime($date)));
            $start = $yesterday_start . ' 00:00:00';
            $end = $yesterday_start . ' 23:59:59';
        }
        if ($start && $end) {
            $map['t1.create_time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $map['t1.create_time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $map['t1.create_time'] = ['elt', strtotime($end)];
        }

        $data = Db::name('withdraw t1')
            ->master()
            ->field('t1.*,t2.name')
            ->join('user t2', 't2.id = t1.userid')
            ->where($map)
            ->order('t1.update_time desc, t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);


        $sum = Db::table('withdraw t1')->join('user t2', 't2.id = t1.userid')->where($map)->sum('money');

        $this->assign('sum', $sum);
        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
    
        $this->assign('start', $start);
        $this->assign('end', $end);

        $this->assign('admin', $admin);

        return $this->fetch();
    }

    public function tixianadd()
    {
        $id = input("id/d");

        $state = input("state");
        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) {

                $db = Db::name('withdraw')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $updates = ['state' => $state, 'update_time' => time()];

                $withdraw = Db::name('withdraw')->find($id);

                // 启动事务
                Db::startTrans();
                try {
                    if ($state == 2) {
                        $content = '提现申请驳回';

                        $reason = input('reason');
                        if ($reason) {
                            $updates['reason'] = input('reason');

                            $content .= '。理由：' .$reason;
                        }
                        //返还
                        Income::index($withdraw['userid'], 0, $withdraw['price'] + $withdraw['shouxu'], $content, 1);
                    } else {
                        $datas = json_decode($withdraw['data'], true);

                        $updates['data'] = json_encode($datas, JSON_UNESCAPED_UNICODE);

                        Db::name('platform_balance')->insert(['types' => 1, 'money' => $withdraw['money'], 'content' => '用户(ID:' . $withdraw['userid'] . ')提现', 'create_time' => time()]);
                    }

                    $mergeWhere[] = ['exp',Db::raw("FIND_IN_SET($id,withdraw_ids)")];
                    $merge = Db::name('withdraw_merge')->where($mergeWhere)->find();
                    $merge_ids = explode(',',$merge['withdraw_ids']);
                    array_splice($merge_ids,array_search($id ,$merge_ids),1);
                    Db::name('withdraw_merge')->where(['id'=>$merge['id']])->update([
                        'price' => $merge['price'] - $withdraw['price'],
                        'shouxu' => $merge['shouxu'] - $withdraw['shouxu'],
                        'money' => $merge['money'] - $withdraw['money'],
                        'withdraw_ids' => implode(',',$merge_ids)
                    ]);


                    $res= Db::name('withdraw')->where('id', $id)->update($updates);

                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return ['err' => $e->getMessage()];
                }
                $data = ['ret' => '修改成功'];
            }
        } else {
            if ($id) {
                $name = Db::name('withdraw')->find($id);
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //删除提现记录
    public function tixiandel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('withdraw')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function shenheAll()
    {

        $admin = session('admin', '', 'mmjtAdmin');

        $admin = Db::name('admin')->find($admin['id']);

        if ($admin['type'] != 1) {
            return ['err' => '无权限'];
        }
        // $data = ['err' => '开发中'];
        // return $data;
        if (request()->isAjax()) {
            $post = input('post.');
            $type = input('type');
            $current_time = time();
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $db = Db::name('withdraw');
                foreach ($post as $k => $v) {
                    if ($type == 'del') {
                    } else {
                        if($type == 2){
                            $unshenhe = $db->where(['userid' => $v, 'state' => 0])->select();
                            $pricecount = array_sum(array_column($unshenhe, 'price'));
                            $shouxucount = array_sum(array_column($unshenhe, 'shouxu'));
                            $moneycount = array_sum(array_column($unshenhe, 'money'));
                            $sum = $pricecount + $shouxucount;
                            $unshenhe_ids = array_column($unshenhe, 'id');

                            $content = '提现申请驳回';

                            $reason = input('reason');
                            if ($reason) {
                                $content .= '。理由：' .$reason;
                            }

                            $merge = Db::name('withdraw_merge')->where(['userid' => $v, 'state' => 0])->order('id','desc')->find();
                            if($merge){
                                $merge_ids = explode(',',$merge['withdraw_ids']);
                                foreach ($unshenhe_ids as $key1 => $value1) {
                                    array_splice($merge_ids,array_search($value1 ,$merge_ids),1);
                                }
                                $update = [
                                    'price' => $merge['price'] - $pricecount,
                                    'shouxu' => $merge['shouxu'] - $shouxucount,
                                    'money' => $merge['money'] - $moneycount,
                                    'withdraw_ids' => implode(',',$merge_ids),
                                    'update_time' => $current_time,
                                ];
                                if(sizeof($merge_ids)==0){
                                    $update['state'] = 2;
                                }
                                Db::name('withdraw_merge')->where(['id'=>$merge['id']])->update($update);
                            }
                            //返还
                            Income::index($v, 0, $sum, $content, 1);
                        }else{
                            Db::name('withdraw_merge')->where(['userid' => $v, 'state' => 0])->update(['state' => $type, 'update_time' => $current_time]);
                        }
                        $db->where(['userid' => $v, 'state' => 0])->update(['state' => $type, 'update_time' => $current_time]);
                    }
                }
                if ($db) {
                    $data = ['ret' => '操作成功'];
                } else {
                    $data = ['err' => '操作失败'];
                }
            } else {
                $data = ['err' => '操作失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }
}
